package edu.gatech.cs2340.teamrocket.view.main;

import edu.gatech.cs2340.teamrocket.control.networking.impl.VTNetworkingInterface;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import edu.gatech.cs2340.teamrocket.view.networking.ChatDisplay;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JButton;

@SuppressWarnings("serial")
public class ChatPanel extends JPanel implements ChatDisplay, ActionListener {

    private static final String DEFAULT_CHATFIELD_TEXT = "Enter chat here";

    private final JTextField textField;
    private final JTextArea textArea;

    public ChatPanel() {
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        textField = new JTextField(10);
        textField.setText(DEFAULT_CHATFIELD_TEXT);
        textField.addActionListener(this);
        textField.addFocusListener(new FocusAdapter(){
            public void focusGained(FocusEvent fe){
                textField.setText("");
            }
        });

        textArea = new JTextArea(5, 10);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        //Add Components to this panel.
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1;
        add(textField, gbc);

        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weightx = 0;
        JButton button = new JButton("send");
        button.addActionListener(this);
        add(button, gbc);

        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        add(scrollPane, gbc);
    }


    @Override
    public void recieveChatMessage(String message) {
        textArea.append(message + "\n");
    }

    @Override
    public synchronized void actionPerformed(ActionEvent arg0) {
        String text = textField.getText();
        if(!text.equals("") && !text.equals(DEFAULT_CHATFIELD_TEXT)){
            VTNetworkingInterface.getInstance().sendChatMessage(text);
            textField.setText("");
        }
    }
}
